package com.riguz.forks.framework.route.impl;

import java.util.ArrayList;
import java.util.List;

import com.riguz.forks.framework.mvc.HttpMethod;
import com.riguz.forks.framework.mvc.Request;
import com.riguz.forks.framework.mvc.RequestHandler;
import com.riguz.forks.framework.route.Route;
import com.riguz.forks.framework.route.RouteHandler;

public class RadixTreeRoute implements Route {
    private RouteTree getTree    = new RouteTree();
    private RouteTree postTree   = new RouteTree();
    private RouteTree putTree    = new RouteTree();
    private RouteTree deleteTree = new RouteTree();
    private RouteTree patchTree  = new RouteTree();

    @Override
    public void addRoute(HttpMethod method, String pattern, RequestHandler handler) {
        try {
            switch (method) {
                case GET:
                    this.getTree.addNode(pattern, handler);
                    break;
                case POST:
                    this.postTree.addNode(pattern, handler);
                    break;
                case DELETE:
                    this.putTree.addNode(pattern, handler);
                    break;
                case PUT:
                    this.deleteTree.addNode(pattern, handler);
                    break;
                case PATCH:
                    this.patchTree.addNode(pattern, handler);
                    break;
                default:
                    break;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    @Override
    public RouteHandler resolve(Request request) {
        List<String> args = new ArrayList<>();
        RequestHandler handler = null;
        RouteTree route = null;
        switch(request.getHttpMethod()){
            case GET:
                route = this.getTree;
                break;
            case POST:
                route = this.postTree;
                break;
            case DELETE:
                route = this.putTree;
                break;
            case PUT:
                route = this.deleteTree;
                break;
            case PATCH:
                route = this.patchTree;
                break;
            default:
                return null;
        }
        handler = route.find(request.getRequestPath(), args);
        if(handler == null)
            return null;
        return new RouteHandler(handler, args, "");
    }

    @Override
    public void complete() {
        System.out.println("GET ROUTE:");
        this.getTree.print();
        System.out.println("POST ROUTE:");
        this.postTree.print();
    }

}
